<template>
    <div>
        <!-- 面包屑 -->
        <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item :to="{ path: 'home' }">过程任务</el-breadcrumb-item>
            <el-breadcrumb-item>查看任务</el-breadcrumb-item>
        </el-breadcrumb>

        <h2 style="border-bottom: 1px solid;padding-bottom: 10px;">查看任务</h2>

        <div style="margin: 3% 5% 3% 5%;">
            <!-- 选题详情 -->
            <h1>实践过程任务</h1>
            <div style="margin-top:2%;">
                <el-table :data="processList" @current-change="handleCurrentChange" highlight-current-row height="200"
                    border style="width: 100%; ">
                    <el-table-column prop="practicalType" label="实践类型" :formatter="formatPractical"  align="center"/>
                    <el-table-column prop="courseName" label="实践课程"  align="center"/>
                    <el-table-column prop="processName" label="任务名称" width="180"   align="center"/>
                    <el-table-column prop="processType" label="任务类型"  width="80" :formatter="formatTyoe" align="center" />
                    <el-table-column prop="adviserName" label="老师" width="80"  align="center"/>
                    <el-table-column prop="startDate" label="开始时间" :formatter="formatDate"   align="center"/>
                    <el-table-column prop="endDate" label="截止时间" :formatter="formatDate"   align="center"/>
                    <el-table-column fixed="right" label="操作" width="120"  align="center">
                        <template #default="scope">
                            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">详情</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div style="margin-top: 3%;">
                <div>
                    <el-text style="color: red;">已选中实践：{{currentRow.courseName}}</el-text><br/>
                    <el-text style="color: red;">已选中任务：{{currentRow.processName}}</el-text> 
                </div>
                <el-upload class="upload-demo" drag :action="url" :show-file-list="false" multiple
                    :on-success="uploadFileHandler" :on-error="uploadFileErrorHandler"
                    :on-progress="uploadFileOnProgressHandler" :data=token>
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <!--     <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
                </el-upload>
                
            </div>
            <div style="margin-top: 3%; border-style: dashed; border-color:#545c64; border-width: 0.1px; height: 130px; width: auto;border-radius: 10px;">
                <p style="color: #545c64; font-size: small;text-indent: 2em;">操作规范：</p>
                <p style="color: #545c64; font-size: small;text-indent: 2em;">1.请先选择任务（当前任务条底色改变即是被选中状态）；</p>
                <p style="color: #545c64; font-size: small;text-indent: 2em;">2.选择上传报告按钮；</p>
                <p style="color: #545c64; font-size: small;text-indent: 2em;">3.请将准备好的文件按照正确的格式命名，在指定区域进行上传。</p>
            </div>
        </div>

        <!-- 弹出框 -->
        <div class="notice-form">
            <el-dialog v-model="editDialogVisible" :model="editingRow">
                <h1>{{ editingRow.stuId }}</h1>

                <div style="margin-top: 3%; min-height: 300px;">
                    <el-input v-model="editingRow.content" :disabled="true" type="textarea" autosize="ture"/>
                </div>
                <!-- <el-button>取消</el-button> -->
            </el-dialog>
        </div>
    </div>
</template>
<script   setup>
import { ref, onBeforeMount, reactive, computed } from 'vue';
import { genFileId } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import requests from '@/api/ajax';
import {ElLoading,ElMessage} from 'element-plus';
// import type { TableColumnCtx, TableInstance } from 'element-plus'

// onBeforeMount(() => {

// })

// const asd = requests({ url: "/students/processTask", method: "get", }).then(res => {
//     //存储用户信息到浏览器toke
//     if (res.code === 20041) {
//         const abc = res.rdata
//         processList.value = abc
//     }

// })
//     .catch(err => {
//         console.error(err.data);
//         // 登录请求失败后的操作
//     });

function getProType() {
    requests({ url: "/students/processTask", method: "get", }).then(res => {
        //存储用户信息到浏览器toke
        if (res.code === 20041) {
            processList.value = res.rdata
            for (let i = 0; i < res.rdata.length; i++) {

                const obj = {}
                if (res.rdata[i].practicalType === 0) {
                    obj.text = '过程任务'
                }
                else {
                    obj.text = '最终任务'
                }
                obj.value = res.rdata[i].practicalType
                protype.push(obj)
            }
        }
    })
}
getProType()

const editDialogVisible = ref(false);
const editingRow = ref(
    {
        stuId: '',
        content: ''
    }
);
function handleEdit(row) {
    // 将当前编辑行的数据保存到组件 data 中
    editingRow.value = { ...row };
    // 显示编辑弹窗
    editDialogVisible.value = true;
}

//表格内容
const processList = ref([
    {
        processId: '',
        processName: "",
        processType: '',
        startDate: "",
        endDate: "",
        content: "",
        practicalId: '',
        classId: '',
        className: "",
        adviserId: '',
        adviserName: "",
        teachId: '',
        teachName: "",
        practicalType: '',
        onloadDate: "",
        planId: '',
        courseId: '',
        courseName: "",
        majorName: "",
        enrolDate: ""
    },
])

//实践课题类型选
const protype = reactive([

])

//时间格式化
function formatDate(row, column, cellValue, index) {
    let format = 'YYYY-mm-dd 00:00'
    let date = new Date(cellValue);
    const dataItem = {
        'Y+': date.getFullYear().toString(),
        'm+': (date.getMonth() + 1).toString(),
        'd+': date.getDate().toString(),
    }
    Object.keys(dataItem).forEach((item) => {
        const ret = new RegExp(`(${item})`).exec(format);
        if (ret) {
            format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'));
        }
    });
    /*  dateFilters.value = format */
    //时间选择栏
    /*  let dateFilters = ref([])
     dateFilters = format */
    // for(let i=0 ; i<myPublish.length;i++){
    //   const obj = ref([])
    //   obj.text = 
    /*   myPublish.value.courseDate = ref(format);
      console.log(myPublish.value.courseDate) */
    return format
}

function formatPractical(row, column, cellValue, index){
    let format = '';
    let practicalTypes = cellValue;
    if(practicalTypes === 0){
        format = '课程设计任务';
        return format;
    }else if(practicalTypes === 1){
        format = '校内实践课题';
        return format;
    }else if(practicalTypes === 2){
        format = '校外实践课题';
        return format;  
    }
}

//将任务类型转换为过程任务或最终任务
function formatTyoe(row, column, cellValue, index) {
    let format = ''
    let date = cellValue;
    if (date === 0) {
        format = '过程任务';
    } else if (date === 1) {
        format = '最终任务';
    }
    return format;
}

// interface User {
//     date: string
//     name: string
//     address: string
//     tag: string
// }

// const filterHandler = (
//     value: string,
//     row: User,
//     column: TableColumnCtx<User>
// ) => {
//     const filter = protype.find((item) => item.column === column.prop);
//     filter.confirmButtonText = '确定';
//     filter.resetButtonText = '重置';
//     const property = column['property']
//     return row[property] === value
// }

//文件上传需要的url

let url = ref()

//选中行的值
const currentRow = ref({

})
//表格的点击行触发的函数
const handleCurrentChange = (val) => {
    currentRow.value = val
    url.value = "http://localhost:8080/students/upload/" + currentRow.value.processId + "/" + currentRow.value.practicalId + "/" + currentRow.value.processType
    console.log(url);
}

//以下全部为文件上传需要的内容
const token = ref({
    token: ''
});
token.value.token = localStorage.getItem('user') // 替换为自己的 token
//console.log("++"+token.value);
// token.value = 'Bearer'+ token .value;

function uploadFileHandler(res) {
    setTimeout(() => {
        if (loadingInstance.value !== null) {
            loadingInstance.value.close();
            loadingInstance.value = null;
        }
        if (res.code == 20010) {
            ElMessage.error(res.msg)
        } else {
            ElMessage.success(res.msg)
        }

    }, 1000);
}
function uploadFileErrorHandler(res) {
    ElMessage.error("上传失败,请检查网络连接")
    if (loadingInstance.value !== null) {
            loadingInstance.value.close();
            loadingInstance.value = null;
        }
}

const loadingInstance = ref(null);

function fullScreenLoading() {
    loadingInstance.value = ElLoading.service({
        lock: true,
        text: '文件上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    });

}
function uploadFileOnProgressHandler(res) {
    // this.$message("上传中...")
    fullScreenLoading()
}
</script>